var request = require('request'),
  fs = require('fs'),
  grapesFolder = __dirname+'/grapes/',
  projectFolder = __dirname+'/src/';

function getWebFn(callback){
  var web = {},
    webModule = {};
  request({
    url: 'http://grapes.fwowo.com/web/jjrb/web.json',
    gzip: true
  }, function(error, response, body){
    if (error) {
      console.log('获取grapes-jjrb配置文件失败！');
      console.log(error);
      callback(web, webModule);
    } else {
      web = JSON.parse(body);
      request({
        url: 'http://grapes.fwowo.com/web/jjrb/web_module.json',
        gzip: true
      }, function(error, response, body){
        if (error) {
          console.log('获取grapes-jjrb配置文件失败！');
          console.log(error);
        } else {
          webModule = JSON.parse(body);
        }
        callback(web, webModule);
      });
    }
  });
}

// 生成module文件
function moduleFileFn(moduleList, callback){
  var styleSource = `
html, body{
  margin: 0;
  padding: 0;
  background-color: #fff;
  -webkit-text-size-adjust: none;
}
p {
  margin: 0;
  padding: 0;
}
ul, li{
  list-style: none;
}
a {
  text-decoration: none;
}
`;
  var scriptSource = 'if (!grapes) var grapes = {};\n';
  function eachModule(){
    if (moduleList.length) {
      var _module = moduleList.shift();
      request({
        url: 'http://grapes.fwowo.com/api/onemodule.do',
        method: 'POST',
        body: "id=" + _module
      }, function(error, response, body){
        var moduleData = JSON.parse(body);
        styleSource += '\n/* ' + _module + '*/\n' + moduleData['style'];
        scriptSource += `
grapes["`+_module+`"] = class {
  constructor (param) {
    this.template = \``+moduleData['template']+`\`;
    var param_def = {};
    if (param) {
      for (var key in param) {
        param_def[key] = param[key];
      }
    }
    this.param = param_def;
  }
  init (data) {
    var template = this.template,
      param = this.param;
    `+moduleData['script']+`
  }
}
`;
        eachModule();
      });
    } else {
      fs.writeFileSync(grapesFolder + 'grapes_module.css', styleSource, 'utf-8');
      fs.writeFileSync(grapesFolder + 'grapes_module.js', scriptSource, 'utf-8');

      // 生成一份到项目中
      fs.writeFileSync(projectFolder + 'static/grapes/module.css', styleSource, 'utf-8');
      fs.writeFileSync(projectFolder + 'static/grapes/module.js', scriptSource, 'utf-8');

      callback();
    }
  }
  eachModule();
}

getWebFn(function(web, webModule){
  // 获取moduleList
  var moduleList = [];
  var _webSource = 'if (!newGrapes) var newGrapes = {};';
  for (var _module in webModule) {
    var _moduleId = webModule[_module]['moduleId'];
    if (moduleList.indexOf(_moduleId) < 0) {
      moduleList.push(_moduleId);
    }
    _webSource += '\nnewGrapes["'+_module+'"] = new grapes["'+_moduleId+'"]('+JSON.stringify(webModule[_module]['param'])+');'
  }
  
  fs.writeFileSync(grapesFolder + 'grapes_web.js', _webSource, 'utf-8');
  fs.writeFileSync(projectFolder + 'static/grapes/web.js', _webSource, 'utf-8');

  moduleFileFn(moduleList, function(){
    for (var file in web) {
      var _source = '',
        _data = {},
        _moduleList = web[file]['moduleList'];

      _data = {
        "filename": file,
        "moduleData": []
      };
      for (var i=0; i<_moduleList.length; i++) {
        _data['moduleData'].push({
          "module": _moduleList[i]['module'],
          "data": JSON.stringify(_moduleList[i]['data'])
        });
      }
      fs.writeFileSync(grapesFolder + file + '.html', artTemplate.render(grapeTpl, _data), 'utf-8');
    }
    console.log('生成完成');
  });
});

var artTemplate = require('art-template'),
grapeTpl = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>{{filename}}</title>
<script>
(function(){
  var ua = window.navigator.userAgent.toLocaleLowerCase();
  if (ua.indexOf('iphone') > -1 || ua.indexOf('android') > -1) {
    var _mode = 'mobile',
      _dpr = window.devicePixelRatio || 1,
      _width = window.screen.width * _dpr;
  } else {
    var _mode = 'pc',
      _dpr = 1,
      _htmlWidth = window.outerWidth || 540,
      _width = _htmlWidth < 540 ? _htmlWidth : 540;
      // _width = 375;
  }

  var _rem = _width / 10,
    _meta = document.createElement("meta");
  _meta.setAttribute("name", "viewport");
  _meta.setAttribute("content", "width="+_width+",initial-scale="+(1/_dpr)+",maximum-scale="+(1/_dpr)+",minimum-scale="+(1/_dpr)+",user-scalable=no");
  document.head.appendChild(_meta);
  document.documentElement.style.fontSize = _rem + 'px';

  if (_mode == 'mobile') {
    window.tap = 'tap';
    window.touchstart = "touchstart";
    window.touchmove = "touchmove";
    window.touchend = "touchend";
  } else {
    window.tap = 'click';
    window.touchstart = "mousedown";
    window.touchmove = "mousemove";
    window.touchend = "mouseup";
  }
}());
</script>
<link rel="stylesheet" href="grapes_module.css">
</head>
<body>
<script src="zepto-1.2.0.min.js"></script>
<script src="grapes_module.js"></script>
<script src="grapes_web.js"></script>
<script>
{{each moduleData}}
$('body').append(newGrapes["{{$value.module}}"].init({{$value.data}}));
{{/each}}
</script>
</body>
</html>`;
artTemplate.defaults.escape = false;
